home
lars.st0ne.at
Linux And Related Stuff
[BLOG] |ARCHIVE| |TAG MAP| |OTHER STUFF| |ME|
  • find window by title or class


    #bash #ewmh #openbox #wmctrl #xprop #zenity

    When a workday is over and i start to close all programs, the CTRL-D game begins.

    The same question raises everyday: Why i have started 10 ssh sessions to the same host!?!

    The answer is simple. If i need a session to a host, and i don't find an open one within 5 seconds, i start to get impatient and open a new terminal.

    To find my terminals faster, i wrote a bash script, which searches through all window titles for the given string. If the filter matches, it brings up all relevant windows. The search string is entered via a zenity dialog box.

    Important: The script only works with a EWMH compliant window manager.

    prerequisites:
    The following packages have to be installed:
    - zenity
    - wmctrl
    - xprop

    The script should be triggered by a keyboard shortcut. ( ... see my last post how to configure a keyboard shortcut in openbox )

    switch_to_window.sh:

    #!/bin/bash
    
    win_list="init"
    
    # read key
    key=$( zenity --entry --text 'find window:' )
    [ "$key" = "" ] && { exit 0; }
    
    # get id of the focused window
    active_win_id=$(xprop -root | awk -F'# 0x' '/_NET_ACTIVE_W/{print $2}')
    
    # get list of all windows matching the key
    # the for loop is a workaround for the missing AND operator in the grep command
    for k in $key; do
       if [ "$win_list" = "init" ]; then
          win_list=$(wmctrl -x -l | grep -i $k | grep -ve "0x${active_win_id} " );
       else
          win_list=$(echo "$win_list" | grep -i $k );
       fi
    done
    switch_to=$( echo "$win_list" | cut -d' ' -f 1 )
    
    # exit if no match
    [ "$switch_to" = "" ] && { exit 0; }
    
    # switch through all window in list
    for i in $switch_to; do
       wmctrl -i -a $i;
    done
    

    The search string is case insensitive and can be part of the title or the window class. You can also enter multiple space separated keyword.

    Examples:

    keyword           action
    term          ... brings up all terminals
    lars.st0ne.at ... brings up my browser ( when on page lars.st0ne.at ) and my ssh session to lars.st0ne.at
    term lars     ... brings up only my ssh sessions to lars.st0ne.at
    
    Aug 05 2012 17:46
    by st0ne
    ? hits
    • comment @Twitter
    • share on Twitter
©2012 Robert Steininger aka st0ne
CC-BY-SA